package com.lyh.controller;

import com.lyh.pojo.PersonAndUser;
import com.lyh.pojo.Result;
import com.lyh.pojo.User;
import com.lyh.service.UserService;
import com.lyh.utils.HtmlCode;
import com.lyh.utils.RegexUtils;
import com.lyh.utils.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserService userService;

    @Autowired
    JavaMailSenderImpl mailSender;

    @PostMapping("/login")
    @ResponseBody
    public Result<String> login(String identify, String password){

        Result<String> result = new Result<>();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();

        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(identify, password);

        try {
            subject.login(token);
            //登陆成功
            result.setFlag(true);
            //设置调准url, 跳转到首页
            result.setUrl(HtmlCode.getHost()+"/index");
            return result;
        } catch (UnknownAccountException e) {
            logger.error("用户名不存在!!!");
        } catch (IncorrectCredentialsException e){
            logger.error("密码错误!!!");
        } catch (Exception e) {
            logger.error("用户认证, 未知错误!!!");
        }
        result.setFlag(false);
        result.setMsg("用户名或密码错误！");
        return result;
    }

    @RequestMapping("/register")
    @ResponseBody
    Result<String> register(PersonAndUser personAndUser, HttpSession session, String checkCode,Model model){
        String code = (String) session.getAttribute("code");
        if(code!=null)
            if(!code.equalsIgnoreCase(checkCode)){
                return ResultUtils.getResult(false,"验证码错误!请重新输入",1);
            }
        /*
         * 二次校验数据是否符合要求
         */
        boolean flag = false;
        if (RegexUtils.notNull(personAndUser.getBirthday()))
            if (RegexUtils.checkEmail(personAndUser.getEmail()))
                if (RegexUtils.notNull(personAndUser.getGender()))
                    if (RegexUtils.checkIdentify(personAndUser.getIdentify()))
                        if (RegexUtils.checkUsernameAndPassword(personAndUser.getPassword()))
                            if (RegexUtils.checkPhone(personAndUser.getPhone()))
                                if (RegexUtils.notNull(personAndUser.getRealname()))
                                    if (RegexUtils.checkUsernameAndPassword(personAndUser.getUsername()))
                                        flag = true;
        if(!flag)
            return ResultUtils.getResult(false,"请正确填写个人信息!",2);


        //通过验证
        //注册之前还需要查重, 手机号码, 邮箱, 身份证号
        Result<String> result = userService.checkDuplicate(personAndUser);

        if(!result.isFlag()){
            return result;
        }

        //用户信息还没有被注册
        //存储到数据库中, 并且发送激活邮件
        int r = userService.register(personAndUser);

        //存储成功
        if ( r == 1 ){
            //跳转到激活提示信息页面
            String msg = "注册成功!请在48小时内查看邮箱激活邮件以激活账号";
            String host = HtmlCode.getHost();
            String url = host+"/haveToLogin/2";
            return ResultUtils.getResult(true,host+"/msg?status=1&msg="+msg+"&url="+url);
        }
        return ResultUtils.getResult(false,"请正确填写个人信息!",2);
    }

    @RequestMapping("/logout")
    String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

    @RequestMapping("/active/{username}/{active}")
    String active(@PathVariable("username") String username, @PathVariable("active") String active, Model model){

        //激活状态 0.激活码错误 1.该用户激活成功 2.该用户已是激活状态
        int activeStation = userService.active( username, active );


        if(activeStation == 1){
            model.addAttribute("status",1);
            model.addAttribute("msg","欢迎登陆12354山卡拉火车网, 您的用户已被成功激活!");
        } else if (activeStation == 2){
            model.addAttribute("status",2);
            model.addAttribute("msg","您的用户已被激活, 请勿再次激活!");
        } else if (activeStation == 0){
            model.addAttribute("status",0);
            model.addAttribute("msg","信息错误, 请输入正确的用户名和对应的激活码!");
        }

        model.addAttribute("url",HtmlCode.getHost()+"/index");
        return "msg";//这是一个显示信息的页面

    }

    @RequestMapping("/checkName/{username}")
    @ResponseBody
    Result<String> checkUsername(@PathVariable("username")String name){
        Result<String> re = new Result<>();
        User user = userService.queryUserByUsername(name);
        if(user!=null){
            re.setFlag(false);
            re.setMsg("该用户名已注册!");
            return re;
        }
        re.setFlag(true);
        re.setMsg("用户名可用");
        return re;
    }


}
